package com.weaver.qfengx;

import cn.hutool.http.HttpRequest;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.*;
import java.util.Map;

/**
 * 基于hutool httpRequest 的简单包装
 * Auther: YeShengtao
 * Date: 2023/9/18 下午10:21
 */
public class HttpTools {

    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    //检查客户端证书，若不信任该证书抛出异常，咱们自己就是客户端不用检查
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
                    //检查服务器的证书，若不信任该证书抛出异常，可以不检查默认都信任
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
                    //返回受信任的X509证书数组
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    public static String post(String url, Map<String, Object> params, boolean ignoreSSL) {
        HttpRequest httpRequest = null;
        if (url.startsWith("https://") && ignoreSSL) {
            httpRequest = HttpRequest.post(url)
                    .header("Content-Type", "application/x-www-form-urlencoded").setSSLSocketFactory(getSSLSocketFactory());
        } else {
            httpRequest = HttpRequest.post(url)
                    .header("Content-Type", "application/x-www-form-urlencoded");
        }
        String result = httpRequest.form(params)
                .execute().body();
        return result;
    }

    public static String post(String url, Map<String, Object> params) {
        return post(url, params, true);
    }


}
